import React, { useState, useRef, useEffect } from 'react'
import './Home.css'
import { Document, Packer, Paragraph, TextRun, HeadingLevel, AlignmentType } from 'docx'
import MarkdownIt from 'markdown-it'

const md = new MarkdownIt()

export default function Home() {
  const [messages, setMessages] = useState([
    {
      id: 1,
      type: 'bot',
      content: '你好！我是智能教育助手，我可以帮你生成各种教育文档。请告诉我你需要什么类型的文档？',
      timestamp: new Date()
    }
  ])
  const [inputMessage, setInputMessage] = useState('')
  const [loading, setLoading] = useState(false)
  const [uploadedFiles, setUploadedFiles] = useState([])
  const [conversationId, setConversationId] = useState('')
  const messagesEndRef = useRef(null)
  const inputRef = useRef(null)
  const fileInputRef = useRef(null)

  // API基础URL
  const API_BASE = 'http://localhost:3001/api/dify'
  const DOCUMENTS_API_BASE = 'http://localhost:3001/api/documents'

  // 自动滚动到底部
  const scrollToBottom = () => {
    messagesEndRef.current?.scrollIntoView({ behavior: "smooth" })
  }

  useEffect(() => {
    scrollToBottom()
  }, [messages])

  // 添加消息到列表
  const addMessage = (content, type = 'user') => {
    const newMessage = {
      id: Date.now() + Math.random(), // 确保ID唯一性
      type,
      content,
      timestamp: new Date()
    }
    setMessages(prev => [...prev, newMessage])
  }

  // 显示状态消息
  const showStatus = (message, type = 'info') => {
    const statusMessage = {
      id: Date.now() + Math.random(),
      type: 'system',
      content: `⚠️ ${message}`,
      timestamp: new Date()
    }
    setMessages(prev => [...prev, statusMessage])
    setTimeout(() => {
      setMessages(prev => prev.filter(msg => msg.id !== statusMessage.id))
    }, 5000)
  }

  // 文件上传处理
  const handleFileUpload = async (event) => {
    const files = Array.from(event.target.files)
    if (files.length === 0) return

    setLoading(true)
    showStatus('正在上传文件...')

    try {
      const uploadPromises = files.map(async (file) => {
        const formData = new FormData()
        formData.append('file', file)

        const token = localStorage.getItem('token');
        const response = await fetch(`${API_BASE}/upload-file`, {
          method: 'POST',
          headers: {
            'Authorization': token ? (token.startsWith('Bearer ') ? token : `Bearer ${token}`) : ''
          },
          body: formData
        })

        if (!response.ok) {
          throw new Error(`文件上传失败: ${file.name}`)
        }

        const result = await response.json()
        return {
          fileId: result.fileId,
          name: file.name,
          type: file.type,
          size: file.size,
          extractedContent: result.extractedContent
        }
      })

      const uploadedFileResults = await Promise.all(uploadPromises)
      setUploadedFiles(prev => [...prev, ...uploadedFileResults])
      
      showStatus(`成功上传 ${uploadedFileResults.length} 个文件`)
      addMessage(`📎 已上传文件: ${uploadedFileResults.map(f => f.name).join(', ')}`, 'system')
    } catch (error) {
      console.error('文件上传错误:', error)
      showStatus(`文件上传失败: ${error.message}`)
    } finally {
      setLoading(false)
      if (fileInputRef.current) {
        fileInputRef.current.value = ''
      }
    }
  }

  // 移除已上传的文件
  const removeUploadedFile = (fileId) => {
    setUploadedFiles(prev => prev.filter(f => f.fileId !== fileId))
  }

  // 下载文档
  const downloadDocument = async (content, title, format = 'markdown') => {
    let blob;
    let filename;
    
    // 处理内容，确保是字符串格式
    let documentContent = content;
    if (typeof content === 'object') {
      // 如果是对象，尝试提取document字段
      if (content.document) {
        documentContent = content.document;
      } else if (content.answer) {
        documentContent = content.answer;
      } else {
        documentContent = JSON.stringify(content);
      }
    }
    
    // 确保documentContent是字符串
    if (typeof documentContent !== 'string') {
      documentContent = String(documentContent);
    }
    
    if (format === 'markdown' || format === 'text') {
      blob = new Blob([documentContent], { type: 'text/markdown;charset=utf-8' });
      filename = `${title}.md`;
    } else if (format === 'html') {
      const htmlContent = `
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>${title}</title>
    <style>
        body { font-family: 'Microsoft YaHei', Arial, sans-serif; line-height: 1.6; margin: 40px; }
        h1, h2, h3 { color: #333; }
        pre { background: #f5f5f5; padding: 15px; border-radius: 5px; overflow-x: auto; }
        code { background: #f0f0f0; padding: 2px 4px; border-radius: 3px; }
    </style>
</head>
<body>
${documentContent}
</body>
</html>`;
      blob = new Blob([htmlContent], { type: 'text/html;charset=utf-8' });
      filename = `${title}.html`;
    } else if (format === 'docx') {
      // 转换Markdown为DOCX
      const docxBlob = await convertMarkdownToDocx(documentContent, title);
      blob = docxBlob;
      filename = `${title}.docx`;
    } else {
      blob = new Blob([documentContent], { type: 'text/plain;charset=utf-8' });
      filename = `${title}.txt`;
    }
    
    const url = URL.createObjectURL(blob);
    const link = document.createElement('a');
    link.href = url;
    link.download = filename;
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
    URL.revokeObjectURL(url);
  }

  // Markdown转DOCX函数
  const convertMarkdownToDocx = async (markdownContent, title) => {
    try {
      console.log('开始转换Markdown到DOCX:', markdownContent);
      
      // 简化处理：直接按行处理Markdown内容
      const lines = markdownContent.split('\n');
      const children = [];

      // 添加标题
      children.push(
        new Paragraph({
          text: title,
          heading: HeadingLevel.HEADING_1,
          alignment: AlignmentType.CENTER,
          spacing: {
            after: 200,
            before: 200
          }
        })
      );

      // 逐行处理内容
      for (const line of lines) {
        const trimmedLine = line.trim();
        
        if (!trimmedLine) {
          // 空行
          children.push(
            new Paragraph({
              text: '',
              spacing: { after: 100 }
            })
          );
        } else if (trimmedLine.startsWith('# ')) {
          // 一级标题
          children.push(
            new Paragraph({
              text: trimmedLine.substring(2),
              heading: HeadingLevel.HEADING_1,
              spacing: { after: 200, before: 200 }
            })
          );
        } else if (trimmedLine.startsWith('## ')) {
          // 二级标题
          children.push(
            new Paragraph({
              text: trimmedLine.substring(3),
              heading: HeadingLevel.HEADING_2,
              spacing: { after: 200, before: 200 }
            })
          );
        } else if (trimmedLine.startsWith('### ')) {
          // 三级标题
          children.push(
            new Paragraph({
              text: trimmedLine.substring(4),
              heading: HeadingLevel.HEADING_3,
              spacing: { after: 150, before: 150 }
            })
          );
        } else if (trimmedLine.startsWith('- ') || trimmedLine.startsWith('* ')) {
          // 列表项
          children.push(
            new Paragraph({
              children: [
                new TextRun({
                  text: `• ${trimmedLine.substring(2)}`,
                  size: 24,
                  font: 'Microsoft YaHei'
                })
              ],
              spacing: { after: 100, before: 50 },
              indent: { left: 720 }
            })
          );
        } else if (trimmedLine.startsWith('```')) {
          // 代码块标记，跳过
          continue;
        } else {
          // 普通段落
          children.push(
            new Paragraph({
              children: [
                new TextRun({
                  text: trimmedLine,
                  size: 24,
                  font: 'Microsoft YaHei'
                })
              ],
              spacing: { after: 150, before: 100 }
            })
          );
        }
      }

      // 创建DOCX文档
      const doc = new Document({
        sections: [
          {
            properties: {
              page: {
                margin: {
                  top: 1440, // 1 inch
                  right: 1440,
                  bottom: 1440,
                  left: 1440
                }
              }
            },
            children: children
          }
        ]
      });

      // 生成DOCX文件
      const buffer = await Packer.toBlob(doc);
      return buffer;
    } catch (error) {
      console.error('DOCX转换失败:', error);
      // 如果转换失败，返回纯文本格式
      const fallbackBlob = new Blob([markdownContent], { type: 'text/plain;charset=utf-8' });
      return fallbackBlob;
    }
  }

  // 检查是否为文档生成提示词
  const isDocumentGenerationPrompt = (message) => {
    const lowerMessage = message.toLowerCase()
    const documentKeywords = [
      '生成', '创建', '制作', '写一个', '写一份',
      '课程', '大纲', '教案', '教学', '考试', '题目', '试题',
      '学习', '指南', '文档', '报告', '计划', '方案'
    ]
    return documentKeywords.some(keyword => lowerMessage.includes(keyword))
  }

  // 处理用户输入
  const handleSendMessage = async () => {
    if (!inputMessage.trim() || loading) return

    const userMessage = inputMessage.trim()
    setInputMessage('')
    addMessage(userMessage, 'user')
    setLoading(true)

    try {
      // 判断是否为文档生成提示词
      if (isDocumentGenerationPrompt(userMessage)) {
        // 调用documents接口生成文档
        const documentResult = await generateDocumentFromMessage(userMessage)
        
        if (documentResult.success && documentResult.data && documentResult.data.document) {
          // 创建可下载的文档消息格式
          const documentContent = {
            content: documentResult.data.document,
            title: documentResult.data.metadata?.title || '生成的文档'
          }
          addMessage(documentContent, 'download')
        } else if (documentResult.answer) {
          // 对于answer格式的回复，也标记为文档
          const documentContent = {
            content: documentResult.answer,
            title: '生成的文档'
          }
          addMessage(documentContent, 'download')
        } else {
          addMessage('文档生成失败，请重试。', 'bot')
        }
      } else {
        // 普通对话，调用dify接口
        const response = await fetch(`${API_BASE}/chat-messages`, {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json'
          },
          body: JSON.stringify({
            message: userMessage,
            files: uploadedFiles,
            conversationId: conversationId
          })
        })

        if (!response.ok) {
          throw new Error(`请求失败: ${response.status}`)
        }

        // 处理流式响应
        const reader = response.body.getReader()
        const decoder = new TextDecoder()
        let botMessage = ''
        let messageId = null

        while (true) {
          const { done, value } = await reader.read()
          if (done) break

          const chunk = decoder.decode(value, { stream: true })
          const lines = chunk.split('\n')

          for (const line of lines) {
            if (line.startsWith('data: ')) {
              try {
                const data = JSON.parse(line.slice(6))
                
                if (data.event === 'message') {
                   if (!messageId) {
                     messageId = Date.now() + Math.random()
                     const newMessage = {
                       id: messageId,
                       type: 'bot',
                       content: '',
                       timestamp: new Date()
                     }
                     setMessages(prev => [...prev, newMessage])
                   }
                   botMessage += data.answer
                   // 更新消息内容
                   setMessages(prev => prev.map(msg => 
                     msg.id === messageId ? { ...msg, content: botMessage } : msg
                   ))
                } else if (data.event === 'message_end') {
                  if (data.conversation_id) {
                    setConversationId(data.conversation_id)
                  }
                }
              } catch (e) {
                // 忽略解析错误
              }
            }
          }
        }

        if (!botMessage) {
          addMessage('收到您的消息，但没有获得有效回复。', 'bot')
        }
      }

      // 清空已上传的文件（可选，根据需求决定）
      // setUploadedFiles([])

    } catch (error) {
      console.error('发送消息错误:', error)
      addMessage(`❌ 请求失败: ${error.message}`, 'bot')
    } finally {
      setLoading(false)
    }
  }

  // 从用户消息生成文档
  const generateDocumentFromMessage = async (message) => {
    try {
      // 改进的意图识别
      const lowerMessage = message.toLowerCase()
    
    let docType = 'general'
    let title = ''
    let subject = ''
    let grade = ''
    let format = 'markdown'

    // 识别文档类型
    if (lowerMessage.includes('课程') || lowerMessage.includes('大纲')) {
      docType = 'course_outline'
      title = '课程大纲'
    } else if (lowerMessage.includes('教案') || lowerMessage.includes('教学')) {
      docType = 'lesson_plan'
      title = '教案设计'
    } else if (lowerMessage.includes('考试') || lowerMessage.includes('题目') || lowerMessage.includes('试题')) {
      docType = 'exam_questions'
      title = '考试题目'
    } else if (lowerMessage.includes('学习') || lowerMessage.includes('指南')) {
      docType = 'study_guide'
      title = '学习指南'
    }

    // 提取学科信息
    if (lowerMessage.includes('数学')) subject = '数学'
    else if (lowerMessage.includes('语文')) subject = '语文'
    else if (lowerMessage.includes('英语')) subject = '英语'
    else if (lowerMessage.includes('物理')) subject = '物理'
    else if (lowerMessage.includes('化学')) subject = '化学'
    else if (lowerMessage.includes('生物')) subject = '生物'
    else if (lowerMessage.includes('历史')) subject = '历史'
    else if (lowerMessage.includes('地理')) subject = '地理'
    else subject = '通用'

    // 提取年级信息
    if (lowerMessage.includes('小学')) grade = '小学'
    else if (lowerMessage.includes('初中')) grade = '初中'
    else if (lowerMessage.includes('高中')) grade = '高中'
    else if (lowerMessage.includes('大学')) grade = '大学'
    else grade = '通用'

    // 根据文档类型构建不同的请求内容
    let requestData = {}
    
    if (docType === 'exam_questions') {
      // 考试题目 - 生成具体的题目内容
      requestData = {
        title: `${subject}${title}`,
        subject: subject,
        grade: grade,
        docType: docType,
        format: format,
        requirements: `请生成${grade}${subject}的考试题目，包含选择题、填空题、解答题等题型，题目要符合${grade}学生的认知水平。`
      }
    } else if (docType === 'course_outline') {
      // 课程大纲
      requestData = {
        title: `${subject}课程大纲`,
        subject: subject,
        grade: grade,
        docType: docType,
        format: format,
        requirements: `请为${grade}${subject}课程制定详细的教学大纲，包含教学目标、教学内容、教学进度安排等。`
      }
    } else if (docType === 'lesson_plan') {
      // 教案设计
      requestData = {
        title: `${subject}教案设计`,
        subject: subject,
        grade: grade,
        docType: docType,
        format: format,
        requirements: `请为${grade}${subject}设计一份详细的教案，包含教学目标、教学重难点、教学过程、教学方法等。`
      }
    } else if (docType === 'study_guide') {
      // 学习指南
      requestData = {
        title: `${subject}学习指南`,
        subject: subject,
        grade: grade,
        docType: docType,
        format: format,
        requirements: `请为${grade}${subject}制作一份学习指南，包含学习方法、重点知识、常见问题解答等。`
      }
    } else {
      // 通用文档
      requestData = {
        title: '教育文档',
        subject: subject,
        grade: grade,
        docType: 'general',
        format: format,
        requirements: message
      }
    }

    // 调用API
    const token = localStorage.getItem('token');
    const headers = {
      'Content-Type': 'application/json'
    };
    
    // 如果有token，添加Authorization头部
    if (token) {
      headers['Authorization'] = token.startsWith('Bearer ') ? token : `Bearer ${token}`;
    }
    
    const response = await fetch(`${DOCUMENTS_API_BASE}/generate/technical`, {
      method: 'POST',
      headers: headers,
      body: JSON.stringify(requestData)
    })

    const result = await response.json()
    return result
    } catch (error) {
      console.error('generateDocumentFromMessage 错误:', error)
      return { success: false, error: error.message }
    }
  }

  // 处理回车键发送
  const handleKeyPress = (e) => {
    if (e.key === 'Enter' && !e.shiftKey) {
      e.preventDefault()
      handleSendMessage()
    }
  }

  // 快速回复按钮
  const quickReplies = [
    '生成数学课程大纲',
    '帮我写一个语文教案',
    '出几道英语考试题',
    '制作学习指南',
    '生成物理实验教案'
  ]

  const handleQuickReply = (reply) => {
    setInputMessage(reply)
  }

  // 格式化时间
  const formatTime = (date) => {
    return date.toLocaleTimeString('zh-CN', { 
      hour: '2-digit', 
      minute: '2-digit' 
    })
  }

  return (
    <div className="chat-container">
      <div className="chat-header">
        <div className="chat-title">
          <h1>📚 智能教育助手</h1>
          <p>基于AI的教育文档生成聊天室</p>
        </div>
        <div className="chat-status">
          {loading ? (
            <span className="status-indicator loading">生成中...</span>
          ) : (
            <span className="status-indicator online">在线</span>
          )}
        </div>
      </div>

      <div className="chat-messages">
        {messages.map((message) => (
          <div key={message.id} className={`message ${message.type}`}>
            <div className="message-avatar">
              {message.type === 'bot' ? '🤖' : message.type === 'user' ? '👤' : message.type === 'download' ? '📥' : '⚠️'}
            </div>
            <div className="message-content">
              <div className="message-text">
                {message.type === 'bot' && typeof message.content === 'string' && message.content.includes('#') ? (
                  <pre className="document-preview">{message.content}</pre>
                ) : message.type === 'download' ? (
                  <div className="download-section">
                    <p>📄 文档已生成，点击下方按钮下载：</p>
                    <div className="download-buttons">
                      <button 
                        className="download-btn markdown"
                        onClick={() => downloadDocument(message.content.content, message.content.title, 'markdown')}
                      >
                        📝 下载 Markdown
                      </button>
                      <button 
                        className="download-btn docx"
                        onClick={() => downloadDocument(message.content.content, message.content.title, 'docx')}
                      >
                        📄 下载 DOCX
                      </button>
                      <button 
                        className="download-btn html"
                        onClick={() => downloadDocument(message.content.content, message.content.title, 'html')}
                      >
                        🌐 下载 HTML
                      </button>
                      <button 
                        className="download-btn text"
                        onClick={() => downloadDocument(message.content.content, message.content.title, 'text')}
                      >
                        📄 下载 纯文本
                      </button>
                    </div>
                  </div>
                ) : (
                  <p>{typeof message.content === 'string' ? message.content : JSON.stringify(message.content)}</p>
                )}
              </div>
              <div className="message-time">
                {formatTime(message.timestamp)}
              </div>
            </div>
          </div>
        ))}
        {loading && (
          <div className="message bot">
            <div className="message-avatar">🤖</div>
            <div className="message-content">
              <div className="typing-indicator">
                <span></span>
                <span></span>
                <span></span>
              </div>
            </div>
          </div>
        )}
        <div ref={messagesEndRef} />
      </div>

      <div className="quick-replies">
        {quickReplies.map((reply, index) => (
          <button
            key={index}
            className="quick-reply-btn"
            onClick={() => handleQuickReply(reply)}
            disabled={loading}
          >
            {reply}
          </button>
        ))}
      </div>

      {/* 已上传文件显示区域 */}
      {uploadedFiles.length > 0 && (
        <div className="uploaded-files">
          <div className="uploaded-files-header">
            <span>📎 已上传文件 ({uploadedFiles.length})</span>
          </div>
          <div className="uploaded-files-list">
            {uploadedFiles.map((file) => (
              <div key={file.fileId} className="uploaded-file-item">
                <div className="file-info">
                  <span className="file-icon">
                    {file.type.startsWith('image/') ? '🖼️' : 
                     file.type.includes('pdf') ? '📄' : 
                     file.type.includes('word') ? '📝' : '📁'}
                  </span>
                  <span className="file-name">{file.name}</span>
                  <span className="file-size">({(file.size / 1024).toFixed(1)}KB)</span>
                </div>
                <button 
                  className="remove-file-btn"
                  onClick={() => removeUploadedFile(file.fileId)}
                  title="移除文件"
                >
                  ❌
                </button>
              </div>
            ))}
          </div>
        </div>
      )}

      <div className="chat-input">
        <div className="input-container">
          <div className="input-row">
            <textarea
              ref={inputRef}
              value={inputMessage}
              onChange={(e) => setInputMessage(e.target.value)}
              onKeyPress={handleKeyPress}
              placeholder="发送消息，支持文本、图片和文档..."
              disabled={loading}
              rows="1"
            />
            <div className="input-buttons">
              <input
                ref={fileInputRef}
                type="file"
                multiple
                accept="image/*,.pdf,.doc,.docx"
                onChange={handleFileUpload}
                style={{ display: 'none' }}
              />
              <button
                className="file-btn"
                onClick={() => fileInputRef.current?.click()}
                disabled={loading}
                title="上传文件"
              >
                📎
              </button>
              <button
                className="send-btn"
                onClick={handleSendMessage}
                disabled={!inputMessage.trim() || loading}
              >
                {loading ? (
                  <span className="loading-spinner"></span>
                ) : (
                  '发送'
                )}
              </button>
            </div>
          </div>
        </div>
        <div className="input-tips">
          <p>💡 提示：支持上传图片、PDF、Word文档进行识别和分析</p>
        </div>
      </div>
    </div>
  )
}
